package com.ds.common.route.service;

import com.ds.common.route.agent.Agent;
import com.ds.common.route.agent.AgentService;
import com.ds.common.route.config.ClusterConfig;
import com.ds.common.route.config.ConfigCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 路由中心基础服务
 *
 * @author shenzhao
 */
@Service
public class RouteCenterService {


    ConfigCenterService configCenterService;

    AgentService agentService;

    @Autowired
    public RouteCenterService(ConfigCenterService configCenterService, AgentService agentService) {
        this.configCenterService = configCenterService;
        this.agentService = agentService;
    }

    /**
     * 根据请求定位应该路由到什么集群，优先从请求头里面获得，然后再查询结构tree
     *
     * @param serverName
     * @return
     */
    public ClusterConfig findClusterByServerName(String serverName) {
        return configCenterService.match(findAgentByServerName(serverName));
    }

    public Agent findAgentByServerName(String serverName) {
        String domain = getDomainByServerName(serverName);
        Agent agent = agentService.findAgentByDomain(domain);

        if (agent != null) {
            return agent;
        } else {
            return agentService.getDefaultAgent();
        }

    }

    public static String getDomainByServerName(String serverName) {
        int index = serverName.indexOf(".");
        if (index <= 0) {
            throw new RuntimeException("serverName :" + serverName + " is not valid");
        }
        return serverName.substring(index+1);
    }
}
